const appData = require("../shared/appData");
const axios = require("axios");
const User = require("../models/user");
const { changekeyWord } = require("../utils/changeKeyword");
const { Op } = require("sequelize");
// 登录
exports.login = async function (js_code) {
  const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appData.appid}&secret=${appData.secrect}&js_code=${js_code}&grant_type=authorization_code`;
  const res = await axios.get(url);
  const { session_key, openid } = res.data; // 获取session_key和openid
  console.log(1111, session_key, openid);
  let user = await User.findOne({
    attributes: { exclude: ["updatedAt", "deletedAt"] },
    where: { openid: openid },
  });
  // user存在，已注册
  if (user) {
    user.sessionKey = session_key;
    await user.save();
    user = await User.findOne({
      attributes: { exclude: ["updatedAt", "deletedAt", "sessionKey"] },
      where: { openid: openid },
    });
    user.isRegister = false;
  } else {
    // 找不到user，未注册
    user = {
      isRegister: true,
    };
  }
  return user;
};
// 注册
exports.register = async function (data) {
  const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appData.appid}&secret=${appData.secrect}&js_code=${data.js_code}&grant_type=authorization_code`;
  const res = await axios.get(url);
  const { session_key, openid } = res.data; // 获取session_key和openid
  const { username, sex, age, height, weight, targetWeight, avatar, college } =
    data.userData;

  await User.create({
    openid: openid,
    sessionKey: session_key,
    username,
    sex,
    age,
    height,
    weight,
    targetWeight,
    avatar,
    college,
  });

  let user = await User.findOne({
    attributes: { exclude: ["updatedAt", "deletedAt", "sessionKey"] },
    where: { openid: openid },
  });
  return user;
};

// 修改
exports.modify = async function (userData) {
  const {
    id,
    username,
    sex,
    age,
    height,
    weight,
    targetWeight,
    avatar,
    college,
  } = userData;
  await User.update(
    { username, sex, age, height, weight, targetWeight, avatar, college },
    { where: { id: id }, individualHooks: true }
  );
  return User.findOne({
    attributes: { exclude: ["updatedAt", "deletedAt", "sessionKey"] },
    where: {
      id: id,
    },
  });
};

//获取用户个人信息
exports.getInfo = async function (userId) {
  return User.findOne({
    where: { id: userId },
    attributes: [
      "id",
      "username",
      "avatar",
      "sex",
      "college",
      "score",
      "concernNum",
      "fansNum",
    ],
  });
};

//获取排行版数据
exports.getRank = async function (college) {
  console.log(college);
  //获取积分排行
  let scoreRank = await User.findAll({
    attributes: ["id", "score", "username", "avatar", "college"],
    order: [["score", "DESC"]],
  });
  scoreRank.forEach((item) => {
    item.dataValues.num = item.score;
  });

  scoreRank = scoreRank.slice(0, 10);
  //获取积分排行
  let scoreCollegeRank = await User.findAll({
    where: {
      college
    },
    attributes: ["id", "score", "username", "avatar", "college"],
    order: [["score", "DESC"]],
  });
  scoreCollegeRank.forEach((item) => {
    item.dataValues.num = item.score;
  });
  scoreCollegeRank = scoreCollegeRank.slice(0, 10);

  return {
    scoreRank,
    scoreCollegeRank,
  };
};

// 获取我的积分排行
exports.getMyRank = async function(score){
  let myRank = {};
  const { count } = await User.findAndCountAll({
      where:{
          score:{
              [Op.gt]: score
          } 
      }
  })
  myRank.rankNum = count+1;
  return myRank;
}

// 获取我的积分排行
exports.getMyRankCollege = async function(score,college){
  let myRank = {};
  const { count } = await User.findAndCountAll({
      where:{
          score:{
              [Op.gt]: score
          },
          college
      }
  })
  myRank.rankNum = count+1;
  return myRank;
}
